<template>
  <!-- 质量异常信息表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    :width="!props.isReadonly ? '850px' : '850px'"
    draggable
    @close="closeDialog"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="110"
      v-show="!props.isReadonly"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="异常信息编号" prop="qualityExceptionCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.qualityExceptionCode"
              placeholder="请输入异常信息编号"
              :disabled="true"
              clearable
            />

            <span v-else>{{ formData.qualityExceptionCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="失效模式" prop="failureModeContent">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.failureModeContent"
              placeholder="请输入失效模式"
              :disabled="true"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品/项目名" prop="productProjectName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.productProjectName"
              placeholder="请输入产品/项目名"
              :disabled="true"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="型号/编号" prop="sortCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.sortCode"
              placeholder="请输入型号/编号"
              :disabled="true"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否内部制造" prop="isInternal">
            <el-radio-group
              disabled
              v-model="formData.isInternal"
              v-if="!props.isReadonly"
              @change="changIsInternal"
            >
              <el-radio :label="1">内部生产</el-radio>
              <el-radio :label="0">外部生产</el-radio>
            </el-radio-group>
            <span v-else>{{ formData.isInternal }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formData.isInternal == 0">
          <el-form-item
            label="生产单位"
            :prop="formData.isInternal == 0 ? 'supplyName' : ''"
          >
            <!-- <el-select
              style="width: 100%"
              v-if="!props.isReadonly"
              v-model="formData.supplyId"
              placeholder="请选择生产单位"
              clearable
              disabled
              @change="changSupplyList"
            >
              <el-option
                v-for="item in supplyList"
                :label="`${item.partnerCode}-${item.partnerName}`"
                :value="`${item.id}`"
              />
            </el-select> -->
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.supplyName"
              placeholder="请输入生产单位"
              :disabled="true"
              clearable
            />
            <span v-else>{{ formData.supplyName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="涉及数量" prop="exceptionQuantity">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.exceptionQuantity"
              :disabled="true"
              style="width: 100%"
              placeholder="请输入涉及数量"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="发生地点" prop="occurrenceLocation">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.occurrenceLocation"
              placeholder="请输入发生地点"
              :disabled="true"
              clearable
            />
            <span v-else>{{ formData.occurrenceLocation }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="问题分类" prop="problemTypeCode">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.problemTypeCode"
              placeholder="请选择问题分类"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList('ExceptionType')"
                :key="item.value"
                :label="item.label"
                :value="Number(item.value)"
              />
            </el-select>
            <span v-else>{{ formData.problemTypeCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生产线/过程" prop="lineProcessName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.lineProcessName"
              placeholder="请输入生产线/过程"
              clearable
            />

            <span v-else>{{ formData.lineProcessName }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="产品过程状态" prop="productProcess">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.productProcess"
              placeholder="请选择产品过程状态"
              clearable
              style="width: 100%"
              @change="handleChangeProductProcess"
            >
              <el-option
                v-for="item in materialProcessStateList"
                :key="item.id"
                :label="`${item.materialProcessStateCode}-${item.materialProcessStateContent}`"
                :value="String(item.id)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="责任部门" prop="departmentId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.departmentId"
              placeholder="请选择责任部门"
              clearable
              style="width: 100%"
              @change="handleChangeDepartment"
            >
              <el-option
                v-for="item in organizationList"
                :key="item.id"
                :label="`${item.organizationCode}-${item.organizationName}`"
                :value="item.id"
              />
            </el-select>
            <span v-else>{{ formData.departmentId }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="问题发生频度" prop="problemFrequency">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.problemFrequency"
              placeholder="请输入问题发生频度"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="失效后果及影响" prop="consequenceInfluence">
            <el-input
              v-if="!props.isReadonly"
              maxlength="255"
              show-word-limit
              :autosize="{ minRows: 2, maxRows: 4 }"
              type="textarea"
              v-model="formData.consequenceInfluence"
              placeholder="请输入失效后果及影响"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import dayjs from "dayjs";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QMSQ8DQUALITYPROBLEMPROBLEMSOLVING",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  qualityExceptionCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  productionTypeId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  productionTypeName: [
    { required: true, message: "请选择产品类目名称", trigger: "change" },
  ],
  materialId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  materialCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  materialName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  figureNumber: [{ required: true, message: "请选择图号", trigger: "change" }],
  exceptionQuantity: [
    // { required: true, message: "请输入数量", trigger: "blur" },
  ],
  failureQuantity: [
    // { required: true, message: "请输入失效对应数量", trigger: "blur" },
  ],
  failureMode: [
    { required: true, message: "请选择失效模式", trigger: "change" },
  ],
  occurrenceTime: [
    { required: true, message: "请选择发生时间", trigger: "change" },
  ],
  occurrenceLocation: [
    // { required: true, message: "请选择发生地点", trigger: "change" },
  ],
  informationSourceId: [
    // { required: true, message: "请选择信息来源", trigger: "change" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  informationSourceContent: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  exceptionState: [],
  isInternal: [],
  supplyId: [
    { required: true, message: "请选择生产单位", trigger: "change" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  supplyCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  supplyName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  problemTypeCode: [
    { required: true, message: "请选择问题分类", trigger: "change" },
  ],
  lineProcessName: [
    { required: true, message: "请输入生产线/过程", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  productProcess: [
    { required: true, message: "请选择产品/过程状态", trigger: "change" },
  ],
  problemFrequency: [
    { required: true, message: "请输入问题发生频度", trigger: "blur" },
  ],
  departmentId: [
    { required: true, message: "请选择责任部门", trigger: "change" },
  ],
  consequenceInfluence: [
    // { required: true, message: "请输入失效后果及影响", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  // 质量问题编号
  qualityProblemCode: "",

  exceptionQuantity: 0,
  occurrenceTime: "",

  informationSourceId: "",
  informationSourceContent: "",
  exceptionState: "",
  isInternal: 1,
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",

  // 异常信息编号
  qualityExceptionCode: "",
  // 异常质量id
  qualityExceptionId: "",
  // 问题分类
  problemTypeCode: "",
  // 生产线过程
  lineProcessName: "",
  // 产品项目名称
  productProjectName: "",
  // 问题频率
  problemFrequency: "",
  // 型号编号
  sortCode: "",
  // 产品过程状态
  productProcess: "",
  // 后果及影响
  consequenceInfluence: "",
  // 责任部门id
  departmentId: "",
  // 责任部门编号
  departmentCode: "",
  // 责任部门名称
  departmentName: "",
  // 失效模式
  failureMode: "",
  // 失效模式内容
  failureModeContent: "",
  // 发生地点
  occurrenceLocation: "",
  // 设计数量
  failureQuantity: "",
  //
  supplyId: "",
  supplyCode: "",
  supplyName: "",
  // 涉及数量
  qualityQuantity: 0,

  // 图号编号
  materialProcessCode: "",
  materialProcessName: "",
  materialProcessId: "",
  materialProcessFigure: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        qualityExceptionCode,
        productionTypeId,
        productionTypeName,
        materialId,
        materialCode,
        materialName,
        figureNumber,
        exceptionQuantity,
        failureQuantity,
        failureMode,
        failureModeContent,
        occurrenceTime,
        occurrenceLocation,
        informationSourceId,
        informationSourceContent,
        exceptionState,
        isInternal,
        supplyId,
        supplyCode,
        supplyName,
        raiseUserId,
        raiseUserName,
        isClose,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        assetPhotos,
        materialProcessCode,
        materialProcessName,
        materialProcessId,
        materialProcessFigure,
      } = newVal;
      // 异常信息编号
      formData.qualityExceptionCode = qualityExceptionCode;
      // 异常质量id
      formData.qualityExceptionId = id;
      // 产品项目名称
      formData.productProjectName = materialName;
      // 型号编号
      formData.sortCode = figureNumber;
      // 失效模式
      formData.failureMode = failureMode;
      // 失效模式内容
      formData.failureModeContent = failureModeContent;
      // 发生地点
      formData.occurrenceLocation = occurrenceLocation;
      // 涉及数量
      formData.failureQuantity = failureQuantity;
      formData.supplyId = supplyId;
      formData.supplyCode = supplyCode;
      formData.supplyName = supplyName;
      formData.isInternal = isInternal;
      formData.informationSourceId = informationSourceId;
      formData.exceptionQuantity = exceptionQuantity;
      formData.qualityQuantity = exceptionQuantity;
      formData.materialProcessCode = materialCode;
      formData.materialProcessName = materialName;
      formData.materialProcessId = materialId;
      formData.materialProcessFigure = figureNumber;
      formData.occurrenceTime = occurrenceTime;
      console.log(exceptionQuantity);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.qualityExceptionCode = "";

  formData.exceptionQuantity = 0;

  formData.failureMode = "";
  formData.failureModeContent = "";
  formData.occurrenceTime = "";
  formData.occurrenceLocation = "";
  formData.informationSourceId = "";
  formData.informationSourceContent = "";
  formData.exceptionState = "";
  formData.isInternal = 1;

  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";

  // 异常信息编号
  formData.qualityExceptionCode = "";
  // 异常质量id
  formData.qualityExceptionId = "";
  // 问题分类
  formData.problemTypeCode = "";
  // 生产线过程
  formData.lineProcessName = "";
  // 产品项目名称
  formData.productProjectName = "";
  // 问题频率
  formData.problemFrequency = "";
  // 型号编号
  formData.sortCode = "";
  // 产品过程状态
  formData.productProcess = "";
  // 后果及影响
  formData.consequenceInfluence = "";
  // 责任部门id
  formData.departmentId = "";
  // 责任部门编号
  formData.departmentCode = "";
  // 责任部门名称
  formData.departmentName = "";
  // 失效模式
  formData.failureMode = "";
  // 失效模式内容
  formData.failureModeContent = "";
  // 发生地点
  formData.occurrenceLocation = "";
  formData.supplyId = "";
  formData.supplyCode = "";
  formData.supplyName = "";
  formData.qualityQuantity = 0;
  formData.materialProcessCode = "";
  formData.materialProcessName = "";
  formData.materialProcessId = "";
  formData.materialProcessFigure = "";
}

const loading = ref(false);

/** 质量异常信息保存提交 */
function handleSubmit() {
  console.log(formData);

  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "填报" : "填报";
      await request({
        url: "/qms/q8dqualityproblem/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 产品过程状态列表
const materialProcessStateList = ref([]);
const getMaterialProcessStateList = async () => {
  let res = await request({
    url: "/qms/qmsmaterialprocessstate/getList",
    method: "post",
    data: {},
  }).finally(() => {
    loading.value = false;
  });
  materialProcessStateList.value = res.data;
};

// 供应商列表
const supplyList = ref([]);
async function getSupplyList() {
  let res = await request({
    url: "mdm/mdmpartner/getListByFull",
    method: "post",
    data: {},
  }).finally(() => {
    loading.value = false;
  });
  supplyList.value = res.data;
}

const changSupplyList = (e) => {
  if (e) {
    supplyList.value.forEach((item) => {
      if (item.id == e) {
        formData.supplyName = item.partnerName;
        formData.supplyCode = item.partnerCode;
      }
    });
  } else {
    formData.supplyName = "";
    formData.supplyCode = "";
  }
};

const changIsInternal = (e) => {
  console.log(e);
  formData.supplyId = "";
  formData.supplyName = "";
  formData.supplyCode = "";
};

// 责任部门

const organizationList = ref([]);
const getOrganizationList = async () => {
  let res = await request({
    url: "/system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 4 },
  }).finally(() => {
    loading.value = false;
  });
  organizationList.value = res.data;
  console.log("organizationList", organizationList.value);
};

const handleChangeDepartment = (e) => {
  if (e) {
    organizationList.value.forEach((item) => {
      if (item.id == e) {
        formData.departmentName = item.organizationName;
        formData.departmentCode = item.organizationCode;
      }
    });
  } else {
    formData.departmentName = "";
    formData.departmentCode = "";
  }
};

//改变产品状态
const handleChangeProductProcess = (e) => {
  console.log(e);
  if (e) {
    materialProcessStateList.value.forEach((item) => {
      if (item.id == e) {
        formData.productProcessName = item.materialProcessStateName;
        formData.productProcessContent = item.materialProcessStateContent;
      }
    });
  }
};

onMounted(() => {
  getMaterialProcessStateList();
  getOrganizationList();
  getSupplyList();
});
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
